//
//  SXComposeViewController.swift
//  sina
//
//  Created by shengxinwei on 16/5/28.
//  Copyright © 2016年 shengxinwei. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class SXComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        setupNavBar()
        setupTextView()
        setupToolbar()
        setPictureController()
        
        registerNotifily()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if pictureVc.images.count == 0 {
            textView.becomeFirstResponder()
        }
        
    }
    
    func PictureView() {
            let picVc = SXPictureViewController()
            self.presentViewController(picVc, animated: true) {
                
            }
      
    }

    private func setPictureController() {
        //选择图片控制器设置为子控制器
        self.addChildViewController(pictureVc)
        self.view.addSubview(pictureVc.view)
        //将底部工具视图置顶显示
        self.view.bringSubviewToFront(toolBar)
        pictureVc.view.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    
    private func registerNotifily() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SXComposeViewController.textViewChange(_:)), name: "UIKeyboardWillChangeFrameNotification", object: nil)
    }
    
    @objc func textViewChange(n: NSNotification) {
        let time_t = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //结构体能够直接存放在字典中?   --> 需要转换为 NSValue 才能存储
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        print(time_t,rect)
        let offsetY = -ScreenHeight + rect.origin.y
        UIView.animateWithDuration(time_t, animations: { 
            self.toolBar.snp_updateConstraints(closure: { (make) in
                make.bottom.equalTo(self.view.snp_bottom).offset(offsetY)
            })
            //提前刷新页面
            self.view.layoutIfNeeded()
            
            }) { (_) in
                
        }
    }

    
    //关闭
    @objc private func dismiss() {
        self.dismissViewControllerAnimated(true) { 
            
        }
    }
    
    //发送按钮
    @objc private func send() {
        
        SXNetworkTools.sharedTools.sendStatus(textView.text, images: pictureVc.images) { (responseObject, error) in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发布失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发布成功")
        }


    }
    
    
    
    //MARK: - 懒加载
    private lazy var rightItem: UIBarButtonItem = {
        let btn = UIButton()
        btn.setTitle("发送", forState: .Normal)
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        //设置文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        
        
        btn.addTarget(self, action: #selector(send), forControlEvents: .TouchUpInside)
        
        let BarButton = UIBarButtonItem(customView: btn)
        return BarButton
    }()
    
    private lazy var textView: UITextView = {
        let tv = UITextView()
      //  tv.text = "为何而来,因何而做"
        tv.font = UIFont.systemFontOfSize(18.0)
        //tv.backgroundColor = UIColor.orangeColor()
        tv.textColor = UIColor.darkGrayColor()
        tv.keyboardDismissMode = .OnDrag
        tv.alwaysBounceVertical = true
        tv.delegate = self
        return tv
    }()

    private lazy var placeHolderLabel: UILabel = {
       let lab = UILabel()
        lab.text = "为何而来,因何而做"
        lab.font = UIFont.systemFontOfSize(18.0)
        lab.textColor = UIColor.lightGrayColor()
        return lab
    }()
    //底部工具栏
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var pictureVc: SXPictureViewController = SXPictureViewController()

}


extension SXComposeViewController {
    private func setupNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(dismiss))
        navigationItem.rightBarButtonItem = rightItem
        navigationItem.rightBarButtonItem?.enabled = false
        
        //创建导航栏自定义view
        //WARNING: - 关于首次为nil的问题
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
        let titleLabel = UILabel(title: "发布微博", font: 16.0, textColor: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: SXUserAccountViewModel.sharedAccount.userAccount?.name ?? "", font: 13.0, textColor: UIColor.lightGrayColor(), alignment: .Center)
        
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        titleLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(myView)
            make.top.equalTo(myView)
        }
        nameLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp_bottom)
        }
        
        navigationItem.titleView = myView
        
    }
    
    private func setupTextView() {
        view.addSubview(textView)
        textView.addSubview(placeHolderLabel)
        
        textView.snp_makeConstraints { (make) in
            make.left.top.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight/3)
        }
        placeHolderLabel.snp_makeConstraints { (make) in
            make.left.equalTo(textView).offset(5)
            make.top.equalTo(textView).offset(8)
        }
    }
    
    //设置底部工具栏
    private func setupToolbar() {
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(49)
        }
        
        var items = [UIBarButtonItem]()
        //操作数据 添加UIBarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
                            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        
        for item in itemSettings {
            let imageName = item["imageName"]
            let actionName = item["actionName"]!
            let buttonItem = UIBarButtonItem(imageName: imageName, title: "", target: self, action: Selector(actionName))
            
            items.append(buttonItem)
            //添加弹簧
            let bouncesItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(bouncesItem)
        }
        items.removeLast()
        //添加按钮
        toolBar.items = items
        
    }
    
    @objc private func selectPicture() {
        print("选中图片")
        pictureVc.view.snp_updateConstraints { (make) in
            make.height.equalTo(ScreenHeight / 3 * 2)
        }
    }
    
    @objc private func selectEmoticon() {
        print("选择表情")
    }

    
    
}


extension SXComposeViewController: UITextViewDelegate {
    //当文本框发生变化时候,设置数据
    func textViewDidChange(textView: UITextView) {
        rightItem.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
    }
}





